<script lang="ts" setup>
import { onBeforeUnmount, onMounted, ref } from 'vue';
import { SimpleScrollbar } from '@sa/materials';
import { useRoute } from 'vue-router';
import EZUIKit from 'ezuikit-js';
import { DeviceInfoList, SwitchController } from '@/service/api/bigScreen';
import { getVideoMonitorListApi, getVideoUrlApi } from '@/service/api/businessApi';
import { useProjectStore } from '@/store/modules/project';
import FishSelect from './video-select.vue';
const projectStore = useProjectStore();
// 传感器列表
const list = ref([]);

const route = useRoute();
const projectId = route.query.projectId ? route.query.projectId : '';
const farmId = route.query.farmId ? route.query.farmId : '';

// 获取传感器数据
const getDeviceInfoList = () => {
  const obj = {
    pageNo: 1,
    pageSize: 1000,
    parentId: 0,
    projectId,
    farmId
  };
  //
  DeviceInfoList(obj).then(res => {
    list.value = res.data?.data;
  });
};
const monitorData = ref([]);
const getMonitorList = () => {
  const obj = {
    projectId,
    farmId
  };
  getVideoMonitorListApi(obj).then(res => {
    if (res.data?.data && res.data?.data.length > 0) {
      res.data?.data.forEach((item: any) => {
        item.deviceName = item.name;
      });
      createVideo(res.data?.data[0].serialNumber, res.data?.data[0].channelNo, res.data?.data[0].id);
    }
    monitorData.value = res.data?.data;
  });
};

let myPlayer: any = null;
const createVideo = (serialNumber: any, channelNo: any, id: any, domId = 'my-video') => {
  getVideoUrlApi({ serialNumber, channelNo }).then((res: any) => {
    const data = res.data;
    projectStore.changeCurrentMonitorId(id);
    myPlayer = new EZUIKit.EZUIKitPlayer({
      id: domId,
      accessToken: data.accessToken,
      url: data.url,
      audio: 0,
      width: document.getElementById(domId)?.clientWidth,
      height: document.getElementById(domId)?.clientHeight
    });
    console.log(document.getElementById(domId)?.clientWidth);
    console.log(document.getElementById(domId)?.clientHeight);
  });
};

const playClose = (id = 'my-video') => {
  if (myPlayer === null) return;
  myPlayer.stop();
  myPlayer.destroy();
  myPlayer = null;
  document.getElementById(id)?.remove();
  const targetID = document.createElement('div');
  targetID.setAttribute('id', id);
  targetID.setAttribute('style', 'height: 416px');
  document.getElementById('video-wrapper')?.appendChild(targetID);
};

const videoChange = (url: any, channelNo: any, id: any) => {
  playClose();
  setTimeout(() => {
    createVideo(url, channelNo, id);
  }, 100);
};

const setSwitchController = (id: any, status: any, online: boolean) => {
  if (!online) {
    window.$message?.error('设备离线, 无法操控');
    return;
  }
  SwitchController({
    id,
    status
  }).then(res => {
    if (res.data) {
      list.value.forEach(item => {
        if (item.childDeviceInfo) {
          item.childDeviceInfo.forEach(items => {
            if (items.id === id) {
              items.status = !items.status;
            }
          });
        }
      });
    }
  });
};

/* 监控弹出框逻辑 */
const monitoringModalVisible = ref(false);
const openMonitoringModal = () => {
  monitoringModalVisible.value = true;
  playClose();
  setTimeout(() => {
    const id = document.getElementById(`monitoringDomId`)?.dataset.id;
    const data: any = monitorData.value.find(item => item.id.toString() === id);
    createVideo(data.serialNumber, data.channelNo, data.id, 'my-video-2');
  }, 100);
};

const monitoringModalClose = () => {
  monitoringModalVisible.value = false;
  playClose();
  setTimeout(() => {
    const id = document.getElementById(`monitoringDomId`)?.dataset.id;
    const data: any = monitorData.value.find(item => item.id.toString() === id);
    createVideo(data.serialNumber, data.channelNo, data.id, 'my-video');
  }, 100);
};
/* 监控弹出框逻辑 */

/* 设备控制相关逻辑 */
const setDeviceControlClass = (items: any): string => {
  if (items.status && items.electric === 0) return 'text-red';
  return '';
};
/* 设备控制相关逻辑 */

onMounted(() => {
  getDeviceInfoList();
  getMonitorList();
});

onBeforeUnmount(() => {
  playClose();
});
</script>

<template>
  <div>
    <div class="index-top">
      <div class="header">
        <img src="../../../assets/imgs/breedDetails/title_jk@2x.png" alt="" />
        <FishSelect id="monitoringDomId" :list="monitorData" hide="0" @change="videoChange" />
      </div>
      <div id="video-wrapper" class="video" @dblclick="openMonitoringModal">
        <div id="my-video" style="height: 416px"></div>
      </div>
    </div>
    <div class="index-bto" style="overflow: hidden">
      <div class="header">
        <img style="user-select: none" src="../../../assets/imgs/breedDetails/title_sbjk@2x.png" alt="" />
      </div>
      <div class="warp">
        <SimpleScrollbar>
          <template v-for="item in list">
            <template v-if="item.deviceType == 3 && item.childDeviceInfo">
              <div class="warp-top">
                <div class="title">
                  <span>{{ item.deviceName }}</span>
                  <span :class="item.online ? 'green' : 'red'">· {{ item.online ? '在线' : '离线' }}</span>
                </div>
                <div class="top-warp">
                  <template v-for="items in item.childDeviceInfo">
                    <div v-if="items.deviceType !== 1" class="top-item" :class="setDeviceControlClass(items)">
                      <div class="item-left" :alt="items.deviceName" :title="items.deviceName">
                        {{ items.deviceName }}
                      </div>
                      <div>
                        <span>电流 {{ items.electric || '0' }}</span>
                        <span>电压 {{ items.vol || '0' }}</span>
                        <div>
                          <img
                            v-if="items.status"
                            style="transform: rotate(180deg)"
                            src="../../../assets/imgs/breedDetails/btn_sbjk_on@2x.png"
                            alt=""
                            @click="setSwitchController(items.id, false, item.online)"
                          />
                          <img
                            v-else
                            style="transform: rotate(180deg)"
                            src="../../../assets/imgs/breedDetails/btn_sbjk_off@2x.png"
                            alt=""
                            @click="setSwitchController(items.id, true, item.online)"
                          />
                        </div>
                      </div>
                    </div>
                  </template>
                </div>
              </div>
            </template>

            <template v-if="item.deviceType != 3 && item.childDeviceInfo">
              <div class="warp-bto">
                <div v-for="it in item.childDeviceInfo" class="bto-item">
                  <div class="title">{{ it.deviceName }}</div>
                  <span>电流 {{ it.electric || '0' }}mA</span>
                  <span>电压 {{ it.vol || '0' }}V</span>
                  <span :class="it.status ? 'green' : 'red'">· {{ it.status ? '在线' : '离线' }}</span>
                  <div class="img">
                    <img
                      v-if="it.status"
                      src="../../../assets/imgs/breedDetails/btn_sbjk_on@2x.png"
                      alt=""
                      @click="setSwitchController(it.id, false)"
                    />
                    <img
                      v-else
                      src="../../../assets/imgs/breedDetails/btn_sbjk_off@2x.png"
                      alt=""
                      @click="setSwitchController(it.id, true)"
                    />
                  </div>
                </div>
              </div>
            </template>
          </template>
        </SimpleScrollbar>
      </div>
    </div>

    <AModal
      v-model:open="monitoringModalVisible"
      width="1360"
      :body-style="{ height: '800px' }"
      title="监控"
      :footer="null"
      :after-close="monitoringModalClose"
    >
      <div id="my-video-2" class="h-full w-full"></div>
    </AModal>
  </div>
</template>

<style lang="scss" scoped>
.index {
  &-top {
    width: 804px;
    height: 544px;
    background-image: url('@/assets/imgs/breedDetails/bg_jk@2x.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;

    .header {
      display: flex;
      align-items: center;
      padding-top: 25px;
      margin-left: 20px;

      img {
        width: 69px;
        height: 34px;
      }
    }

    .video {
      width: 740px;
      height: 416px;
      margin: 23px auto;
      video {
        width: 100%;
        height: 100%;
      }
    }
  }

  &-bto {
    width: 804px;
    height: 376px;
    background-image: url('@/assets/imgs/breedDetails/bg_sbjk@2x.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
    overflow: auto;
    .header {
      width: 110px;
      height: 34px;
      padding-top: 25px;
      margin-left: 20px;
    }
    .warp {
      height: 290px;
      overflow: auto;
      margin: 30px;
      .warp-bto {
        display: grid;
        grid-template-columns: repeat(2, minmax(0, 1fr));
        gap: 15px;
        .red {
          color: #ff5353;
        }
        .green {
          color: #59ff42;
        }
        .bto-item {
          margin-bottom: 15px;
          background: linear-gradient(204deg, rgba(63, 228, 255, 0.12) 0%, rgba(255, 255, 255, 0.04) 100%);
          box-shadow: 0px 2px 5px 0px rgba(23, 43, 69, 0.69);
          border: 1px solid #23517e;
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 0 10px;
          .title {
            font-weight: 500;
            font-size: 14px;
            color: #8dd8f2;
          }
          span {
            font-weight: 400;
            font-size: 14px;
            color: #f1f1f1;
          }
          .img {
            width: 45px;
            height: 44px;
            cursor: pointer;
            img {
              width: 100%;
              height: 100%;
            }
          }
        }
      }
      .warp-top {
        padding: 10px;
        background: linear-gradient(204deg, rgba(63, 228, 255, 0.12) 0%, rgba(255, 255, 255, 0.04) 100%);
        box-shadow: 0px 2px 5px 0px rgba(23, 43, 69, 0.69);
        border: 1px solid #23517e;
        .title {
          .red {
            color: #ff5353;
          }
          .green {
            color: #59ff42;
          }
          span {
            &:nth-child(1) {
              font-family: SourceHanSansCN, SourceHanSansCN;
              font-weight: 500;
              font-size: 14px;
              color: #8dd8f2;
            }
            &:nth-child(2) {
              margin-left: 20px;
              font-family: SourceHanSansCN, SourceHanSansCN;
              font-weight: 400;
              font-size: 14px;
            }
          }
        }

        .top-warp {
          display: grid;
          grid-template-columns: repeat(2, minmax(0, 1fr));
          gap: 10px;
          .top-item {
            display: flex;
            align-items: center;
            div {
              &:nth-child(1) {
                width: 30%;
                overflow: hidden;
                color: #f1f1f1;
                white-space: nowrap;
                text-overflow: ellipsis;
              }
              &:nth-child(2) {
                margin-left: 30px;
                display: flex;
                align-items: center;
                justify-content: flex-end;
                span {
                  font-weight: 400;
                  font-size: 14px;
                  color: #f1f1f1;
                  &:nth-child(2) {
                    margin: 0 15px;
                  }
                }
                img {
                  width: 45px;
                  height: 44px;
                  cursor: pointer;
                }
              }
            }
          }
        }
      }
    }
  }
}

.text-red {
  div, span {
    color: red !important;
  }
}
</style>
